<!--
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
 <view class="lg-scroll-view">
   <scroll-view class="lg-scroll-view-el" :scroll-y="y" :scroll-x="x" :scroll-top="scrollTop" :scroll-left="scrollLeft">
     <view :id="id" class="lg-scroll-view-wrapper">
       <slot></slot>
     </view>
   </scroll-view>
 </view>
</template>

<script >
export default {
  name: 'LgScrollView',
  props: {
    direction: {
      type: String,
      default: 'y',
    },
  },
  data() {
    return {
      id: 'l' + Math.random().toString(36).substring(2),
      scrollTop: 0,
      scrollLeft: 0,
    }
  },
  methods: {
    /**
     * 垂直滚动
     * @param value 内部元素id 或 位置
     */
    scrollY(value) {
      if (typeof value === 'string') {
        const query = uni.createSelectorQuery().in(this);
        let wrapper = null;
        query
            .select('#' + this.id)
            .boundingClientRect((data) => {
              wrapper = data;
            })
            .exec();
        query
            .select('#' + value)
            .boundingClientRect((data) => {
              this.scrollTop = data.top - wrapper.top
            })
            .exec();
      } else {
        this.scrollTop = value
      }
    },
    /**
     * 水平滚动
     * @param value 内部元素id 或 位置
     */
    scrollX(value) {
      if (typeof value === 'string') {
        const query = uni.createSelectorQuery().in(this);
        let wrapper = null;
        query
            .select('#' + this.id)
            .boundingClientRect((data) => {
              wrapper = data;
            })
            .exec();
        query
            .select('#' + value)
            .boundingClientRect((data) => {
              this.scrollLeft = data.left - wrapper.left
            })
            .exec();
      } else {
        this.scrollLeft = value
      }
    }
  },
  computed: {
    y() {
      return this.direction.includes('y')
    },
    x() {
      return this.direction.includes('x')
    }
  }
}
</script>

<style lang="scss" scoped>
	.lg-scroll-view {
    position: relative;
    overflow: hidden;
		.lg-scroll-view-el {
      background: var(--app-bg-color);
      box-sizing: border-box;
      position: absolute;
      inset: 0;
    }
	}
</style>